<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2020/11/8
 * Time: 12:33 下午
 */

namespace addons\unidrink\library;

use addons\unidrink\library\feie\HttpClient;
use addons\unidrink\model\Config;
use app\admin\model\unidrink\Printertemplate;
use think\Exception;
use think\Log;

class printer
{

    /**
     * 打印指定模板 指定设备
     * @param int $templateId 模板id
     * @param int $id 设备id
     * @param array $data 替换模板中变量的数组
     */
    public static function printing(int $templateId, int $id, array $data)
    {
        $template = Printertemplate::get($templateId);
        $printer = \app\admin\model\unidrink\Printers::get($id);

        $template = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function ($matches) use ($data) {
            if (isset($data[$matches[1]])) {
                return $data[$matches[1]];
            } else {
                return '';
            }
        }, $template->template);

        switch ($printer->brand_id) {
            case 'zhongwu':
                self::zhongwu($template, $printer);
                break;
            case 'yilianyun':
                self::yilianyun($template, $printer);
                break;
            case 'feie':
                self::feie($template, $printer);
                break;
        }
    }

    /**
     * 打印自定义模板
     * @param string $template 模板字符串
     * @param integer|null $id 如果不指定deviceId的话全部打印机都会打印
     */
    public static function printingTemplate(string $template, int $id = null)
    {
        $printerModel = new \app\admin\model\unidrink\Printers();
        if ($id) {
            $printers = $printerModel->where(['id' => $id])->select();
        } else {
            $printers = $printerModel->where(['enable' => 1])->select();
        }
        if (!empty($printers)) {

            /**
             * @var \app\admin\model\unidrink\Printers $printer
             */
            foreach ($printers as $printer) {
                $tmp = $template;
                switch ($printer->brand_id) {
                    case 'zhongwu':
                        if (is_array($template)) {
                            $tmp = $template['zhongwu'] ?? '中午打印机';
                        }
                        try {
                            self::zhongwu($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("中午打印机报错：" . $e->getMessage());
                        }
                        break;
                    case 'yilianyun':
                        if (is_array($template)) {
                            $tmp = $template['yilianyun'] ?? '易联云打印机';
                        }
                        try {
                            self::yilianyun($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("易联云打印机报错：" . $e->getMessage());
                        }
                        break;
                    case 'feie':
                        if (is_array($template)) {
                            $tmp = $template['feie'] ?? '飞鹅打印机';
                        }
                        try {
                            self::feie($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("飞鹅打印机报错：" . $e->getMessage());
                        }
                        break;
                }
            }
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\unidrink\Printers $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function feie(string $template, \app\admin\model\unidrink\Printers $printer)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => Config::getByName('print_feie_user')['value'],
            'stime' => $time,
            'sig' => sha1(Config::getByName('print_feie_user')['value'] . Config::getByName('print_feie_ukey')['value'] . $time),
            'apiname' => 'Open_printMsg',
            'sn' => $printer->device_id,
            'content' => $template,
            'times' => $printer->number //打印次数
        );
        $client = new HttpClient(Config::getByName('print_feie_ip')['value'], Config::getByName('print_feie_port')['value']);
        if (!$client->post(Config::getByName('print_feie_path')['value'], $msgInfo)) {
            throw new Exception('飞鹅云打印机sn：' . $printer->device_id . '打印失败');
        } else {
            //服务器返回的JSON字符串，建议要当做日志记录起来
            $result = $client->getContent();
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\unidrink\Printers $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function zhongwu(string $template, \app\admin\model\unidrink\Printers $printer)
    {
        $rpc = new \zhongwu\protocol\RpcClient(Config::getByName('print_zhongwu_appid')['value'], Config::getByName('print_zhongwu_appsecret')['value'], 'http://api.zhongwuyun.com');
        $Zprinter = new \zhongwu\Printer($rpc);
        for ($i = 0; $i < $printer->number; $i++) {
            $res = $Zprinter->set_args($printer->device_id, $printer->device_secret)->cloud_print($template);
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\unidrink\Printers $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function yilianyun(string $template, \app\admin\model\unidrink\Printers $printer)
    {
        $config = new \App\Config\YlyConfig(Config::getByName('print_yilianyun_appid')['value'], Config::getByName('print_yilianyun_appsecret')['value']);

        //获取token
        $accessToken = Config::getByName('print_yilianyun_access_token')['value'] ?? '';
        if (empty($accessToken)) {
            $client = new \App\Oauth\YlyOauthClient($config);
            $token = $client->getToken();   //若是开放型应用请传授权码code
            Config::update(['value' => $token->access_token], ['name' => 'print_yilianyun_access_token']);
            $accessToken = $token->access_token;
        }
        // 在获取设备状态那里绑定设备

        //  调取文本打印;
        $print = new \App\Api\PrintService($accessToken, $config);
        for ($i = 0; $i < $printer->number; $i++) {
            $data = $print->index($printer->device_id, $template, time());
            //var_dump($data);exit;
        }
    }
}
